package loadiconhandler

import (
	"fmt"
	"gmap-backend/internal/config"
	"gmap-backend/internal/server/vo"
	"os"
	"path/filepath"
	"strings"
)

type GmapLoadIcon struct {
}

func (owner *GmapLoadIcon) CanHandle(appConfig *config.AppConfig, req *vo.PathReq) (bool, any) {
	urlMatch := strings.HasPrefix(req.Path, "gmap://")
	if !urlMatch {
		return false, nil
	}
	relaPath := strings.TrimSpace(strings.ReplaceAll(strings.TrimPrefix(strings.TrimPrefix(req.Path, "gmap://"), "/"), "/", "\\"))
	return true, relaPath
}

func (owner *GmapLoadIcon) Handle(appConfig *config.AppConfig, req *vo.PathReq, extra any) *vo.LoadIconResp {
	relaPath := extra.(string)
	mdPath := filepath.Join(appConfig.PathConfig.MapsDir, relaPath+".textbundle", "text.md")
	stat, err := os.Stat(mdPath)
	if nil != err {
		panic(fmt.Sprintf("路径不存在：\r\n%s", mdPath))
	}
	if stat.IsDir() {
		panic(fmt.Sprintf("路径应该为文件：\r\n%s", mdPath))
	}
	return &vo.LoadIconResp{Url: SPECIAL_PATH_GMAP}
}
